using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Scheduler;

public partial class RMTMenu : System.Web.UI.Page
{
    protected static String userID = "";
    protected static int userType = -1;
    protected static int totalTherapies = 0;
    protected static RMT rmt = null;
    protected static Customer cust = null;
    protected static Room north = null;
    protected static Room south = null;
    protected static LinkedList<RMT> rmtList = null;
    protected static String selectedRMT = "";
    protected static DateTime rmtSchedDate;

    protected void Page_Load(object sender, EventArgs e)
    {
        if ( Page.IsPostBack )
            return;
        
        Database DB = new Database();
        DB.OpenDB();
        north = new Room(DB, "North");
        south = new Room(DB, "South");

        /* save the user id and user type */
        userID = Context.Items["User_ID"].ToString();
        userType = int.Parse(Context.Items["User_Type"].ToString());

        /* initialize the page for RMTs (or admin) */
        if (userType == 0 || userType == 1)
        {
            /* Get information about the RMT */
            rmt = new RMT(DB, userID);
            
            /* enable the admin related controls */
            if (rmt.IsAdmin)
            {
                LinkedList<String> rmtIDs = DB.readAllRMTs_ID();
                lblNewTherapy.Visible = true;
                txtNewTherapy.Visible = true;
                btnNewTherapy.Visible = true;

                /* populate the time slot drop down lists */
                for (int i = 0; i < 12; i++)
                {
                    dlstStartHour.Items.Add("" + (8 + i));
                    dlstEndHour.Items.Add("" + (8 + i));
                }

                foreach (String rmtID in rmtIDs)
                {
                    dlstRMTID.Items.Add(rmtID);
                }
                dlstStartMin.Items.Add("00");
                dlstStartMin.Items.Add("30");
                dlstEndMin.Items.Add("00");
                dlstEndMin.Items.Add("30");
                
                dlstRMTID.Visible = true;
                dlstStartMin.Visible = true;
                dlstStartHour.Visible = true;
                dlstEndHour.Visible = true;
                dlstEndMin.Visible = true;
                btnAddRMTSched.Visible = true;
                btnRemoveRMTSched.Visible = true;
                lblStartTime.Visible = true;
                lblEndTime.Visible = true;
                lblRmtID.Visible = true;
                calRMTSched.Visible = true;
                dlstRMTSchedRoom.Visible = true;
                lblRMTRoom.Visible = true;
               
            }

            /* show the controls related to RMT's */
            btnAddTherapyPrice.Visible = true;
            btnRemoveTherapyPrice.Visible = true;
            lblDuration.Visible = true;
            lblPrice.Visible = true;
            txtDuration.Visible = true;
            txtPrice.Visible = true;
            lblChooseTherapy.Visible = true;
            dlstTherapies.Visible = true;

            /* get the number of therapies this RMT currently provides */
            totalTherapies = rmt.TherapyList.Count; 
            
            /* update the Welcome label */
            lblName.Text = "Welcome " + rmt.Name + " (ID: " + rmt.ID + ")";
            /* 
             * get the user's name and display it, because
             * the logged in user might want to change it
             */
            txtName.Text = rmt.Name;    
            
            /* refresh the list of therapies */
            vRefreshTherapyList(DB);
            
            /* view therapy price list for this RMT */
            viewTherapyPriceList(rmt);
            tblTherapyPrice.Visible = true;
        }
        /* intialize controls for the customer */
        else if (userType == 2)
        {
            /* 
             * Get all the RMT objects from db
             */
            rmtList = DB.readAllRMTs();

            /* Get the customer info from db */
            cust = new Customer(DB, userID);
            
            /* show the customer related controls */
            lblChooseRMT.Visible = true;
            btnViewTherPriceList.Visible = true;
            btnBookAppointment.Visible = true;
            dlstRMT.Visible = true;
            dlstRMT.Items.Clear();
            foreach (RMT rmt in rmtList)
            {
                dlstRMT.Items.Add(rmt.Name);
            }
            dlstRMT.SelectedIndex = 0;
            lblName.Text = "Welcome " + cust.Name + " (ID: " + cust.ID + ")";
            txtName.Text = cust.Name;    // get the customer name and display it, because
            viewAppointments();
        }
        else
        {
            return;
        }
        
        /* close the database connection */
        DB.CloseDB();
    }

    /*
     * This method refreshes the list of all the therapies 
     * in the drop down list
     */
    protected void vRefreshTherapyList(Database DB)
    {
        dlstTherapies.Items.Clear();
        LinkedList<Therapy> therapyTypes = Therapy.readAllTherapies(DB);

        foreach (Therapy therapy_type in therapyTypes)
        {
            dlstTherapies.Items.Add(therapy_type.Name);
        }
    }
    
    /*
     * This method adds/updates the provided therapy price information
     */
    protected void btnAddTherapyPrice_Click(object sender, EventArgs e)
    {
        int intDuration = 0;
        int intPrice = 0;

        /* read the price and duration from the controls */
        if (txtDuration.Text != "" && txtDuration.Text != null)
            intDuration = Convert.ToInt32(txtDuration.Text);
        if (txtPrice.Text != "" && txtPrice.Text != null)
            intPrice = Convert.ToInt32(txtPrice.Text);

        Therapy newTherapy = new Therapy(dlstTherapies.SelectedValue);
        TherapyPrice newPrice = new TherapyPrice(intDuration, intPrice);
        newTherapy.PriceList.AddFirst(newPrice);

        Database DB = new Database();
        DB.OpenDB();
        /* add the given therapy price info for this RMT */
        rmt.addTherapy(DB, newTherapy);
        DB.CloseDB();

        /* refresh the page */
        Context.Items["User_ID"] = userID;
        Context.Items["User_Type"] = userType.ToString();
        Server.Transfer("UserProfile.aspx");
    }
    /*
     * This method updates the name for the logged in user
     */
    protected void txtSave_Click(object sender, EventArgs e)
    {
        Database DB = new Database();
        DB.OpenDB();
        if (userType == 0 || userType == 1)
        {
            rmt.Name = txtName.Text;
            rmt.writeToDatabase(DB);
        }
        else if (userType == 2)
        {
            cust.Name = txtName.Text;
            cust.writeToDatabase(DB);
        }
        DB.CloseDB();

        /* refresh the page */
        Context.Items["User_ID"] = userID;
        Context.Items["User_Type"] = userType.ToString();
        Server.Transfer("UserProfile.aspx");
    }
    
    /*
     * This method adds a new therapy type to the system (used by admin)
     */
    protected void btnNewTherapy_Click(object sender, EventArgs e)
    {
        Database db = new Database();
        db.OpenDB();
        String TherapyName = txtNewTherapy.Text;
        Therapy therapy = new Therapy(TherapyName);
        therapy.writeToDatabase(db, therapy.TherapyID);
        vRefreshTherapyList(db);
        viewTherapyPriceList(rmt);
        db.CloseDB();
    }

    /*
     * This method removes a given therapy price for the current RMT
     */
    protected void btnRemoveTherapyPrice_Click(object sender, EventArgs e)
    {
        Database db = new Database();
        Therapy therapy = new Therapy(dlstTherapies.SelectedValue);
        int intDuration = 0;
        int intPrice = 0;

        db.OpenDB();

        if (txtDuration.Text != "" && txtDuration.Text != null)
            intDuration = Convert.ToInt32(txtDuration.Text);
        if (txtPrice.Text != "" && txtPrice.Text != null)
            intPrice = Convert.ToInt32(txtPrice.Text);

        TherapyPrice therapyPrice = new TherapyPrice(intDuration, intPrice);

        /* remove therapy price info from db */
        rmt.removeTherapyPrice(db, therapy.TherapyID, therapyPrice);

        db.CloseDB();

        Context.Items["User_ID"] = userID;
        Context.Items["User_Type"] = userType.ToString();
        Server.Transfer("UserProfile.aspx");
    }

    /*
     * This method handles the click action for the room schedule button
     */
    protected void btnRoomSched_Click(object sender, EventArgs e)
    {
        /*
         * schedule is not visible - show it
         */
        if (workSched.Visible == false)
        {
            String roomName = dlstRoom.SelectedValue;
            Room curRoom = null;
            btnRoomSched.Text = "Hide Room Schedule";

            if (roomName == "")
                return;
            if (roomName == "North")
                curRoom = north;
            else if (roomName == "South")
                curRoom = south;
            else
                return;
            /* show room schedule */
            viewRoomSchedule(curRoom, userType);
            workSched.Visible = true;
            workSched.Focus();
            /* for RMT's refresh the price list table */
            if (userType != 2)
            {
                viewTherapyPriceList(rmt);
            }
            else
            {
                viewAppointments();
            }
        }
        else
        {
            btnRoomSched.Text = "View Room Schedule";
            /* for RMT's refresh the price list table */
            if (userType != 2)
            {
                viewTherapyPriceList(rmt);
            }
            else
            {
                viewAppointments();
            }
            workSched.Visible = false;
        }
    }

    /*
     * This method displays/hides the schedule for the given room
     */
    protected void viewRoomSchedule(Room curRoom, int type)
    {
        workSched.Rows.Clear();
        /* heading row (Name of the days) */
        TableRow curRow = new TableRow();
        TableCell curHeading = new TableCell();
        curHeading.Text = curRoom.Name + " - Schedule";
        curHeading.Font.Bold = true;
        curHeading.Font.Size = FontUnit.Large;
        curHeading.Width = 110;
        curHeading.Wrap = true;
        curRow.Cells.Add(curHeading);

        /* add the column headings for the table (name of the days) */
        for (int i = 0; i < curRoom.WeekSchedule.Length; i++)
        {
            /* populate the cell information */
            curHeading = new TableCell();
            curHeading.Text = curRoom.WeekSchedule[i].Day;
            curHeading.Font.Bold = true;
            curHeading.Width = 80;
            curHeading.Wrap = true;
            /* add the cell to the current row */
            curRow.Cells.Add(curHeading);
        }
        /* add the row to the table */
        workSched.Rows.Add(curRow);

        /* populate the information for each schedule slot */
        for (int i = 0; i < curRoom.WeekSchedule[0].DaySchedule.Length; i++)
        {
            curRow = new TableRow();
            curHeading = new TableCell();
            DateTime time = new DateTime(2007, 11, 20, (i / 2) + 8, (i % 2) * 30, 0);
            curHeading.Text = time.ToShortTimeString();
            curRow.Cells.Add(curHeading);

            /* for each day in the week */
            for (int j = 0; j < curRoom.WeekSchedule.Length; j++)
            {
                TableCell curCell = new TableCell();
                if (type == 0)
                {
                    curCell.Text = curRoom.WeekSchedule[j].DaySchedule[i].detailedSchedForRMTAdmin();
                }
                else if (type == 1)
                {
                    curCell.Text = curRoom.WeekSchedule[j].DaySchedule[i].detailedSchedForRMT(rmt.Name);
                }
                else if (type == 2)
                {
                    curCell.Text = curRoom.WeekSchedule[j].DaySchedule[i].detailedSchedForCustomer(cust.Name);
                }
                curCell.Font.Size = FontUnit.Smaller;
                curRow.Cells.Add(curCell);
            }
            workSched.Rows.Add(curRow);
        }
    }

    /*
     * This method shows the therapy price list for the given RMT 
     */
    protected void viewTherapyPriceList(RMT curRmt)
    {
        TableRow curRow;
        TableCell curHeading;
        tblTherapyPrice.Rows.Clear();
        foreach (Therapy therapy in curRmt.TherapyList) // Cycle through the therapies
        {
            /* add the therapy prices if there are any */
            if (therapy.PriceList.Count != 0)
            {
                curRow = new TableRow();
                curHeading = new TableCell();
                curHeading.Text = therapy.Name;
                curHeading.Font.Bold = true;
                curHeading.Font.Size = FontUnit.Medium;
                curRow.Cells.Add(curHeading);
                curRow.BackColor = System.Drawing.Color.Gainsboro;
                tblTherapyPrice.Rows.Add(curRow);

                foreach (TherapyPrice price in therapy.PriceList)
                {
                    curRow = new TableRow();
                    TableCell curCell = new TableCell();
                    curCell.Text = "Duration: " + price.Duration + " (mins) Price: $" + price.Price;
                    curCell.Font.Size = FontUnit.Small;
                    curRow.Cells.Add(curCell);
                    tblTherapyPrice.Rows.Add(curRow);
                }
            }
        }
    }
    protected void dlstRMT_SelectedIndexChanged(object sender, EventArgs e)
    {
        selectedRMT = dlstRMT.SelectedValue;
    }
    /*
     * This method handles the click even for "View Therapy Price List" 
     */
    protected void btnViewTherPriceList_Click(object sender, EventArgs e)
    {
        selectedRMT = dlstRMT.SelectedValue;

        foreach (RMT curRMT in rmtList)
        {
            if (curRMT.Name == selectedRMT)
            {
                Database db = new Database();
                RMT temp = null;
                /* the RMT object is partially populated (by design) */
                if (curRMT.TherapyList.Count == 0)
                {
                    db.OpenDB();
                    /* load all the information for this rmt from db */
                    temp = db.readRMT(curRMT.ID);
                    db.CloseDB();
                    viewTherapyPriceList(temp);
                }
                else
                {
                    viewTherapyPriceList(curRMT);
                }
                tblTherapyPrice.Visible = true;

                if (temp != null)
                {
                    /* 
                     * update the rmtList with the new 
                     * rmt object
                     */
                    rmtList.Remove(temp);
                    rmtList.AddLast(temp);
                }
                break;
            }
        }
        viewAppointments();
    }
    /*
     * log the user out and go to the Login page
     */
    protected void btnLogOut_Click(object sender, EventArgs e)
    {
        Server.Transfer("UserLogin.aspx");
    }
    
    /*
     * This method redirects the user (customer) to the appointment booking page
     */
    protected void btnBookAppointment_Click(object sender, EventArgs e)
    {
        Context.Items["User_ID"] = userID;
        Server.Transfer("booking.aspx");
    }

    /*
     * This method adds the provided schedule slot for the selected
     * RMT and the selected room
     */
    protected void btnAddRMTSched_Click(object sender, EventArgs e)
    {
        Database db = new Database();
        String rmtID = dlstRMTID.SelectedValue;
        Room curRoom = null;

        int startHour = int.Parse(dlstStartHour.SelectedValue), 
            startMin = int.Parse(dlstStartMin.SelectedValue), 
            endHour = int.Parse(dlstEndHour.SelectedValue), 
            endMin = int.Parse(dlstEndMin.SelectedValue);

        db.OpenDB();

        RMT curRmt = new RMT(db, rmtID);

        if (dlstRMTSchedRoom.SelectedValue == "North")
        {
            curRoom = north;
        }
        else
        {
            curRoom = south;
        }

        if (curRmt != null)
        {
            TimeSlot newTS = new TimeSlot( rmtSchedDate.Year, rmtSchedDate.Month, rmtSchedDate.Day, startHour,
                                            startMin, endHour, endMin );
            curRmt.addTimeSlot(db, newTS);
            if (curRoom.addRmtSched(db, curRmt, newTS))
            {
                lblFailed.Visible = false;
                lblSuccess.Visible = true;
            }
            else
            {
                lblSuccess.Visible = false;
                lblFailed.Visible = true;
            }
        }

        db.CloseDB();
    }

    /*
     * This method removes the provided schedule slot for the selected
     * RMT and the selected room
     */
    protected void btnRemoveRMTSched_Click(object sender, EventArgs e)
    {
        Database db = new Database();
        String rmtID = dlstRMTID.SelectedValue;
        int startHour = int.Parse(dlstStartHour.SelectedValue), 
            startMin = int.Parse(dlstStartMin.SelectedValue), 
            endHour = int.Parse(dlstEndHour.SelectedValue), 
            endMin = int.Parse(dlstEndMin.SelectedValue);

        db.OpenDB();

        RMT curRmt = new RMT(db, rmtID);

        if (curRmt != null)
        {
            TimeSlot newTS = new TimeSlot(rmtSchedDate.Year, rmtSchedDate.Month, rmtSchedDate.Day, startHour,
                                            startMin, endHour, endMin);
            curRmt.removeTimeSlot(db, newTS);
            if (north.removeRMTSched(db, curRmt, newTS))
            {
                lblFailed.Visible = false;
                lblSuccess.Visible = true;
            }
            else
            {
                lblSuccess.Visible = false;
                lblFailed.Visible = true;
            }
        }
    }

    /*
     * This method refreshes and displays the appointment information
     * for the current customer
     */
    protected void viewAppointments()
    {
        foreach (Appointment curApp in cust.AppointmentList)
        {
            TableRow curRow = new TableRow();
            TableCell curCell = new TableCell();
            curCell.Text = curApp.ToString();
            curRow.Cells.Add(curCell);

            tblAppointments.Rows.Add(curRow);
        }
        tblAppointments.Visible = true;
    }

    protected void calRMTSched_SelectionChanged(object sender, EventArgs e)
    {
        rmtSchedDate = calRMTSched.SelectedDate;
    }
}
